 
import java.security.*;
import java.util.Arrays;

import javax.crypto.*;
import javax.crypto.spec.*;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
   
public class Aes implements Ciphers{
	
	@Override
	public String encryptWord(String w, CryptoKey k) {
		try {
			SecretKeySpec sskey= new SecretKeySpec(k.byteArrayKey, "AES");
			Cipher c = Cipher.getInstance("AES");
			c.init(Cipher.ENCRYPT_MODE, sskey);
			byte[] encrypted =c.doFinal(w.getBytes());
			return bytesToString(encrypted);
		} catch (Exception e) {
			System.out.println("An error thrown during encryption");
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String decryptWord(String w, CryptoKey k) {
		String dec = null;
		try {
			SecretKeySpec sskey= new SecretKeySpec(k.byteArrayKey, "AES");
			Cipher c = Cipher.getInstance("AES");
			c.init(Cipher.DECRYPT_MODE, sskey);
			byte[] decrypted = c.doFinal(hexToBytes(w));
			dec = new String(decrypted);
		} catch (Exception e) {
			System.out.println("An error thrown during decryption");
			e.printStackTrace();
		}
		return dec;
	}
	
	public static String asHex(byte[] encrypted) {
		StringBuffer strbuf = new StringBuffer(encrypted.length * 2);
        int i;
        for (i = 0; i < encrypted.length; i++) {
            if (((int) encrypted[i] & 0xff) < 0x10)
                strbuf.append("0");
            strbuf.append(Long.toString((int) encrypted[i] & 0xff, 16));
        }
       return strbuf.toString();
	}
	
	public static String bytesToString(byte[] bytes) {
	    HexBinaryAdapter adapter = new HexBinaryAdapter();
	    String s = adapter.marshal(bytes);
	    return s;
	}

	public static byte[] hexToBytes(String hexString) {
	    HexBinaryAdapter adapter = new HexBinaryAdapter();
	    byte[] bytes = adapter.unmarshal(hexString);
	    return bytes;
	}

}
